<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue';

import { Apis } from '#/api';

const emit = defineEmits(['select']);

const selectedKeys = ref<string[]>(['0-0-0', '0-0-1']);
const checkedKeys = ref<string[]>(['0-0-0', '0-0-1']);
watch(selectedKeys, () => {
  // console.log('selectedKeys', selectedKeys);
});
watch(checkedKeys, () => {
  // console.log('checkedKeys', checkedKeys);
});

const treeData = ref<any[]>([]);

async function getDeptTree() {
  const data = await Apis.system.user.get_deptTree();
  // 递归处理树形结构，将 label 重命名为 title
  const renameLabelToTitle = (nodes: any[]) => {
    return nodes.map((item) => {
      const newItem = { ...item, title: item.label, key: item.id };
      if (item.children) {
        newItem.children = renameLabelToTitle(item.children);
      }
      return newItem;
    });
  };

  treeData.value = renameLabelToTitle(data.list);
}

function handleSelect(selectedKeys, info) {
  emit('select', selectedKeys, info);
}

onMounted(() => {
  getDeptTree();
});
</script>
<template>
  <div class="h-full">
    <p class="mb-2 font-bold">部门列表</p>
    <a-tree
      v-if="treeData.length > 0"
      v-model:checked-keys="checkedKeys"
      v-model:selected-keys="selectedKeys"
      :tree-data="treeData"
      default-expand-all
      @select="handleSelect"
    >
      <template #title="{ title }">
        <span>{{ title }}</span>
      </template>
    </a-tree>
  </div>
</template>
